<?php
/**
 * 七夕游戏
 */
namespace app\mobile\controller;

use app\portal\model\PortalLostModel;
use app\portal\model\PortalPostModel;
use dragon\Activity\QixiScore;
use dragon\SysConfig;
use dragon\User\User;
use think\Db;

class QixiController extends BaseController
{
    // 排名
    public function rank() {
        $list = Db::name('qixi_score')->order('highest_score desc')->limit(10)->select();

        $list = $list->toArray();
        foreach($list as $key => $val) {
            $user = User::get($val['user_id']);
            $list[$key]['nickname'] = $user['user_nickname'];
            $list[$key]['highest_score'] = $val['highest_score'] / 1000;
        }

        $my = Db::name('qixi_score')->where(['user_id' => $this->user['id']])->find();
        if(!$my) {
            $my['highest_score'] = 0;
        }
        $my['nickname'] = $this->user['user_nickname'];
        $my['highest_score'] = $my['highest_score'] / 1000;

        return $this->success([
            'rank'  => $list,
            'my'    => $my,
        ]);
    }

    // 我的成绩
    public function my() {
        $my = Db::name('qixi_score')->where(['user_id' => $this->user['id']])->find();
        if(!$my) {
            $my['highest_score'] = 0;
        }

        return $this->success($my);
    }

    // 提交分数
    public function submit() {
        $score = $this->request->param('score', '', 'floatval');
        $myScore = QixiScore::get(['user_id' => $this->user['id']]);

        if($myScore) {
            $data = [];
            $data['score'] = $score;
            $data['times'] = $myScore['times'] + 1;
            if($score > $myScore['highest_score']) {
                $data['highest_score'] = $score;
            }
        } else {
            $data = [
                'user_id' => $this->user['id'],
                'highest_score' => $score,
                'score' => $score,
                'times' => 1,
            ];
            $myScore = new QixiScore();
        }

        $myScore->save($data);

        return $this->success('success');
    }

}
